package com.jxtc.enterprise.delivery.service;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jxtc.enterprise.common.entity.DeliveryRider;
import com.jxtc.enterprise.common.exception.LoginFailureException;
import com.jxtc.enterprise.common.mapper.RiderMapper;
import com.jxtc.enterprise.delivery.vo.login.RiderLoginSuccessVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class RiderLoginService {
    /**
     * 登录过期时间，单位：天
     */
    private final int tokenExpAtDays = 30;
    /**
     * 登录过期时间，单位：毫秒
     */
    public final long LOGIN_EXPIRE_TIME = 1000L * 60 * 60 * 24 * tokenExpAtDays;
    /**
     * JWT 加密密钥
     */
    public final String RIDER_LOGIN_JWT_KEY = "aiyi2SZFDR0P0i6HRODlbhd5wqmhE5HrRhYPePXAmmBRCbluN9lh1xiZJSxtMHUWnw0_vmd3bK-6DQfVyt87bw";


    private final RiderMapper riderMapper;

    public RiderLoginSuccessVO login(String phone, String password) {
        // SELECT * FROM delivery_rider_t
        // WHERE phone = ? AND del_flag = 0
        // ORDER BY create_time DESC
        LambdaQueryWrapper<DeliveryRider> queryWrapper = new LambdaQueryWrapper<DeliveryRider>()
                .eq(DeliveryRider::getPhone, phone)
                .eq(DeliveryRider::getDelFlag, false)
                .orderByDesc(DeliveryRider::getCreateTime);
        List<DeliveryRider> riders = riderMapper.selectList(queryWrapper);
        if (riders == null || riders.isEmpty()) {
            // 如果找不到 phone 对应的骑手数据，向前端返回错误提示信息
            throw new LoginFailureException("账号或密码错误");
        }

        // 以最新且未被删除的骑手信息作为依据
        DeliveryRider rider = riders.get(0);
        // TODO: 当前密码以明码形式保存在数据库中
        if (!rider.getPassword().equals(password)) {
            // 如果密码不匹配，向前端返回错误提示信息
            throw new LoginFailureException("账号或密码错误");
        }

        String token = JWT.create()
                .setPayload("role", "rider")
                .setPayload("userId", rider.getId())
                .setPayload("name", rider.getName())
                .setExpiresAt(new Date(System.currentTimeMillis() + LOGIN_EXPIRE_TIME))
                .setKey(RIDER_LOGIN_JWT_KEY.getBytes())
                .sign();

        // TODO: 将 token 存储到 Redis 中，当前除了 admin 和 tenant，其它端侧登录的 Token 均为放入 Redis 中
        RiderLoginSuccessVO vo = new RiderLoginSuccessVO();
        vo.setRiderId(rider.getId());
        vo.setRiderName(rider.getName());
        vo.setRiderPhone(rider.getPhone());
        vo.setToken(token);

        return vo;
    }
}
